import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { useAuthStore } from './authStore';

export const useFavoritesStore = defineStore('favorites', () => {
  const authStore = useAuthStore();
  const favorites = ref([]);

  // 从 localStorage 加载收藏数据
  const loadFavorites = () => {
    try {
      if (authStore.currentUser) {
        const userFavorites = localStorage.getItem(`favorites_${authStore.currentUser.username}`);
        favorites.value = userFavorites ? JSON.parse(userFavorites) : [];
      } else {
        favorites.value = [];
      }
    } catch (error) {
      console.error('Error loading favorites:', error);
      favorites.value = [];
    }
  };

  // 保存收藏数据到 localStorage
  const saveFavorites = () => {
    try {
      if (authStore.currentUser) {
        localStorage.setItem(
          `favorites_${authStore.currentUser.username}`,
          JSON.stringify(favorites.value)
        );
      }
    } catch (error) {
      console.error('Error saving favorites:', error);
    }
  };

  // 添加收藏
  const addFavorite = (item) => {
    if (!authStore.currentUser) {
      throw new Error('请先登录');
    }
    
    // 检查是否已经收藏
    const exists = favorites.value.some(fav => fav.id === item.id);
    if (!exists) {
      favorites.value.push({
        ...item,
        addedAt: new Date().toISOString()
      });
      saveFavorites();
    }
  };

  // 取消收藏
  const removeFavorite = (itemId) => {
    if (!authStore.currentUser) {
      throw new Error('请先登录');
    }
    
    const index = favorites.value.findIndex(fav => fav.id === itemId);
    if (index !== -1) {
      favorites.value.splice(index, 1);
      saveFavorites();
    }
  };

  // 检查是否已收藏
  const isFavorite = (itemId) => {
    return favorites.value.some(fav => fav.id === itemId);
  };

  // 获取收藏列表
  const getFavorites = computed(() => {
    return favorites.value.sort((a, b) => 
      new Date(b.addedAt) - new Date(a.addedAt)
    );
  });

  // 获取收藏数量
  const getFavoritesCount = computed(() => favorites.value.length);

  // 初始化
  loadFavorites();

  // 监听用户登录状态变化
  if (authStore) {
    watch(() => authStore.currentUser, () => {
      loadFavorites();
    });
  }

  return {
    favorites,
    addFavorite,
    removeFavorite,
    isFavorite,
    getFavorites,
    getFavoritesCount,
    loadFavorites
  };
}); 